package com.bookmarket.shiro;

import com.bookmarket.entity.Admin;
import com.bookmarket.service.HJHLoginService;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Set;

public class MyRealm extends AuthorizingRealm {

    @Resource
    private HJHLoginService hJHLoginServices;

    /**
     * 用于的权限的认证。
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String name = principalCollection.getPrimaryPrincipal().toString() ;

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo() ;
        Set<String> rolename = hJHLoginServices.findRoles(name) ;
        Set<String> permissions = hJHLoginServices.findPermissions(name) ;

        info.setRoles(rolename);
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * 首先执行这个登录验证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        //获取用户账号
        String name = token.getPrincipal().toString() ;
        Admin user = hJHLoginServices.findUserByUserName(name) ;
        if (user != null){
            //将查询到的用户账号和密码存放到 authenticationInfo用于后面的权限判断。第三个参数传入realName。
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getName(),user.getPass(),
                    "a") ;

            return authenticationInfo ;
        }else{
            return  null ;
        }
    }



    public HJHLoginService gethJHLoginServices() {
        return hJHLoginServices;
    }

    public void sethJHLoginServices(HJHLoginService hJHLoginServices) {
        this.hJHLoginServices = hJHLoginServices;
    }
}